package com.liangtian.mdm.system.permission.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.utils.ResultObject;
import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.system.log.SysLogUtil;
import com.liangtian.mdm.system.log.model.SysLog;
import com.liangtian.mdm.system.log.model.SysLogEnum;
import com.liangtian.mdm.system.log.service.SysLogService;
import com.liangtian.mdm.system.permission.model.SysPermission;
import com.liangtian.mdm.system.permission.service.SysPermissionService;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.util.ConstantBean;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * <p>Encoding    :  UTF-8</p>
 * <p>Package Name: com.liangtian.mdm.system.controller </p>
 * <p>Project Name: chccig-dm </p>
 * <p>Copyright   :  Copyright(c) 2016 石化盈科信息技术有限责任公司 </p>
 * <p>Created Time: 2016-04-26 09:43</p>
 * <p>Description : 权限控制器</p>
 *
 * @author : hj
 * @version :  1.0
 */
@Controller
@RequestMapping("/sysPermission")
public class SysPermissionController extends BaseController {

    //日志
    private static final Logger logger = LoggerFactory.getLogger(SysPermissionController.class);

    //注入权限接口对象
    @Autowired
    SysPermissionService sysPermissionService;

    //日志model
    SysLog sysLog = new SysLog();

    //当前用户
    ////@Value("${ConstantBean.CURRENT_SESSION_USER}")
    //private String ConstantBean.CURRENT_SESSION_USER;


    //日志服务接口对象
    @Autowired
    SysLogService sysLogServiceImpl;

    /**
     * @return 权限列表页面
     * @desc 跳转至权限列表页面
     */
    @RequestMapping(value = "/showViewPermissionList", method = RequestMethod.GET)
    public ModelAndView showViewPermissionList() {    //跳转的页面方法
        ModelAndView view = new ModelAndView();
        view.setViewName("/system/sysPermission/page/sysPermission_list");//跳转到权限页面
        return view;
    }

    /**
     * @return 权限列表页面
     * @desc 跳转至权限新增页面
     */
    @RequestMapping(value = "/showViewPermissionAdd", method = RequestMethod.GET)
    public ModelAndView showViewPermissionAdd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("/system/sysPermission/page/sysPermission_add");
        return view;
    }

    /**
     * @param permission 权限对象
     * @desc 查询全部权限信息
     */
    @RequestMapping(value = "/queryAllPermissionList", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject queryAllPermissionList(SysPermission permission) {
        PageInfo pageInfo = sysPermissionService.queryAllPermission(permission);
        ResultObject result = new ResultObject(pageInfo, permission.getDraw());
        return result;
    }

    /**
     * @param permission 权限对象
     * @return 新增权限的结果
     * @desc 新增权限
     */
    @RequestMapping(value = "/insertPermission", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject insertPermission(SysPermission permission, HttpServletRequest request) {
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        permission.setCreateDate(new Date());
        permission.setPermissionStatus(1);
        permission.setCreateUserId(user.getUserId());
        int count = sysPermissionService.insertSysPermission(permission);//新增方法
        /*sysLog.setUserName(user.getUserName());//用户名
        sysLog.setOperationType("3");//操作类型
        sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
        Date date = new Date();//当前时间
        sysLog.setOperationDate(date);
        if (count>0) {
            sysLog.setOperationContent("用户【"+user.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",权限删除成功");
        }else{
            sysLog.setOperationContent("用户【"+user.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",权限删除失败");
        }
        sysLogServiceImpl.insertLog(sysLog);*/
        SysLogUtil.insertLog("权限新增",
                SysLogEnum.SYS_PERMISSION.getCode(), SysLogEnum.XZ.getCode(), request);
        ResultObject resultObject = new ResultObject(count, "新增权限成功", "新增权限失败");
        return resultObject;//返回结果集
    }

    /**
     * @param ids 需要删除的权限的id
     * @return 批量删除后的结果
     * @desc 批量删除权限
     */
    @RequestMapping(value = "/batchDeletePermission", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject batchDeletePermission(Long[] ids, HttpServletRequest request) {
        List<Long> idsList = Arrays.asList(ids);
        Map<String, Object> params = new HashMap<>();
        params.put("idsList", idsList);//存放
        int count = 0;
        int result = 0;
        count = sysPermissionService.batchDeletePermission(params);//批量删除方法
        result = sysPermissionService.batchDeleteRolePermission(params);//根据资源编号删除中间表
        SysLogUtil.insertLog("删除权限",
                SysLogEnum.SYS_PERMISSION.getCode(), SysLogEnum.SC.getCode(), request);
        
        /*SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        sysLog.setUserName(user.getUserName());//用户名
        sysLog.setOperationType("5");//操作类型
        sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
        Date date = new Date();//当前时间
        sysLog.setOperationDate(date);
        if (count>0 && result>0) {
            sysLog.setOperationContent("用户【"+user.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",权限删除成功");
        }else{
            sysLog.setOperationContent("用户【"+user.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",权限删除失败");
        }
        sysLogServiceImpl.insertLog(sysLog);*/
        ResultObject resultObject = new ResultObject(count, "批量删除权限成功", "批量删除权限失败");
        return resultObject;//返回结果集
    }

    /**
     * @param permissionId
     * @return 编辑权限信息页面
     * @desc 跳转至编辑权限信息页面
     */
    @RequestMapping(value = "/showEditPermissionIdView", method = RequestMethod.GET)
    public ModelAndView showEditPermissionIdView(Long permissionId) {
        ModelAndView view = new ModelAndView();
        //通过权限id获取权限信息
        Map<String, Object> params = new HashMap<>();
        params.put("permissionId", permissionId);
        Map<String, Object> permission = sysPermissionService.queryDocumentByPermission(params);
        view.addObject("permission", permission);//存放对象
        view.setViewName("/system/sysPermission/page/sysPermission_edit");//跳转到编辑界面
        return view;
    }

    /**
     * @param permission 修改权限传递对象
     * @return 修改后的结果
     * @desc 修改权限
     */
    @RequestMapping(value = "/updatePermission", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject updatePermission(SysPermission permission, HttpServletRequest request) {
        permission.setCreateDate(new Date());//当前时间
        int count = sysPermissionService.updatePermission(permission);//编辑方法
        /*SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        sysLog.setUserName(user.getUserName());//用户名
        sysLog.setOperationType("5");//操作类型
        sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
        Date date = new Date();//当前时间
        sysLog.setOperationDate(date);
        if (count>0) {
            sysLog.setOperationContent("用户【"+user.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",权限编辑成功");
        }else{
            sysLog.setOperationContent("用户【"+user.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",权限编辑失败");
        }
        sysLogServiceImpl.insertLog(sysLog);*/
        SysLogUtil.insertLog("编辑权限",
                SysLogEnum.SYS_PERMISSION.getCode(), SysLogEnum.BJ.getCode(), request);
        ResultObject resultObject = new ResultObject(count, "修改权限成功", "修改权限失败");
        return resultObject;
    }

    /**
     * @param ids    返回的权限编号
     * @param status 返回的权限状态
     * @return 编辑权限信息页面
     * @desc 修改权限的状态
     */
    @RequestMapping(value = "/editPermissionStatus", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject editPermissionStatus(Long[] ids, Long status, HttpServletRequest request) {
        int count = 0;
        Map<String, Object> params = new HashMap<>();
        List<Long> idsList = Arrays.asList(ids);
        params.put("idsList", idsList);
        params.put("permissionStatus", status);
       /* SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        sysLog.setUserName(user.getUserName());//用户名
        sysLog.setOperationType("4");//操作类型
        sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
        Date date = new Date();//当前时间
        sysLog.setOperationDate(date);*/
        try {
            count = sysPermissionService.editPermissionStatus(params);
            if (status == 0) {
                SysLogUtil.insertLog("权限停用",
                        SysLogEnum.SYS_PERMISSION.getCode(), SysLogEnum.TY.getCode(), request);
            } else {
                SysLogUtil.insertLog("权限启用",
                        SysLogEnum.SYS_PERMISSION.getCode(), SysLogEnum.QY.getCode(), request);
            }
            /*if (count>0) {
                if (status==0) {
                    sysLog.setOperationContent("用户【"+user.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",权限禁用成功");
                }else {
                    sysLog.setOperationContent("用户【"+user.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",权限启用成功");
                }
            }
            sysLogServiceImpl.insertLog(sysLog);*/
        } catch (Exception e) {
            /*if (status==0) {
                sysLog.setOperationContent("用户【"+user.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",权限禁用失败");
            }else {
                sysLog.setOperationContent("用户【"+user.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",权限启用失败");
            }
            sysLogServiceImpl.insertLog(sysLog);*/
            e.printStackTrace();
        }
        ResultObject resultObject = new ResultObject(count, "修改权限的状态成功", "修改权限的状态失败");
        return resultObject;
    }

    /**
     * @return 权限信息页面
     * @desc 查询权限树
     */
    @RequestMapping(value = "/queryPermissionTree", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject queryPermissionTree() throws IOException {
        Map<String, Object> queryParamsMap = new HashMap<>();
        queryParamsMap.put("permissionStatus", 1);
        List<Map<String, Object>> permissionMapList = sysPermissionService.queryPermissionMapListForTree(queryParamsMap);
        JSONArray treeArray = new JSONArray();
        JSONObject mo = new JSONObject();
        mo.put("id", 0);
        mo.put("name", "资源选择");
        mo.put("pId", "");
        mo.put("type", 0);
        mo.put("open", true);
        treeArray.add(mo);
        //构建ztree
        if (permissionMapList != null && permissionMapList.size() > 0) {
            for (Map map : permissionMapList) {
                JSONObject obj = new JSONObject();
                obj.put("id", map.get("permissionId"));
                obj.put("pId", map.get("parentPermissionId"));
                obj.put("name", map.get("permissionName"));
                obj.put("type", map.get("permissionFlag"));
                obj.put("open", false);
                treeArray.add(obj);
            }
        }
        ResultObject resultObject = new ResultObject();
        resultObject.setData(treeArray);
        return resultObject;
    }

    /**
     * @param roleId 角色编号
     * @return 编辑权限信息页面
     * @desc 查询权限树
     */
    @RequestMapping(value = "/queryEditPermissionTree", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject queryEditPermissionTree(Long roleId, Long permissionId) throws IOException {
        Map<String, Object> queryParamsMap = new HashMap<>();
        queryParamsMap.put("permissionStatus", 1);
        List<Map<String, Object>> permissionMapList = sysPermissionService.queryPermissionMapListForTree(queryParamsMap);
        //获取所选角色拥有的权限
        JSONArray treeArray = new JSONArray();
        JSONObject mo = new JSONObject();
        mo.put("id", 0);
        mo.put("name", "资源选择");
        mo.put("pId", "");
        mo.put("type", 0);
        mo.put("open", false);
        mo.put("checked", false);
        treeArray.add(mo);
        //获取当前角色拥有的权限
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("roleId", roleId);
        queryParams.put("permissionId", permissionId);
        List<Map<String, Object>> permissionOwnList = sysPermissionService.queryPermissionByRoleId(queryParams);
        //构建ztree
        if (permissionMapList != null && permissionMapList.size() > 0) {
            if (null != permissionOwnList && permissionOwnList.size() > 0) {
                for (Map map : permissionMapList) {
                    boolean flag = false;
                    look:
                    for (Map m : permissionOwnList) {
                        if (m.get("permissionId") == map.get("permissionId") || m.get("permissionId").equals(map.get("permissionId"))) {
                            flag = true;
                            break look;
                        }
                    }
                    JSONObject obj = new JSONObject();
                    obj.put("id", map.get("permissionId"));
                    obj.put("pId", map.get("parentPermissionId"));
                    obj.put("name", map.get("permissionName"));
                    obj.put("type", map.get("permissionFlag"));
                    obj.put("open", true);
                    treeArray.add(obj);
                    if (flag) {
                        obj.put("checked", true);
                    } else {
                        obj.put("checked", false);
                    }
                }
            } else {
                for (Map map : permissionMapList) {
                    JSONObject obj = new JSONObject();
                    obj.put("id", map.get("permissionId"));
                    obj.put("pId", map.get("parentPermissionId"));
                    obj.put("name", map.get("permissionName"));
                    obj.put("type", map.get("permissionFlag"));
                    obj.put("checked", false);
                    obj.put("open", true);
                    treeArray.add(obj);
                }
            }
        }
        ResultObject resultObject = new ResultObject();
        resultObject.setData(treeArray);
        return resultObject;
    }

    /**
     * @param permissionId 资源id
     * @return 查询后返后的结果
     * @desc 根据资源编号查询中间表角色是否和资源关联
     */
    @RequestMapping(value = "/queryRoleByPermissionId", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject queryRoleByPermissionId(int permissionId) {
        SysPermission sysPermission = new SysPermission();
        sysPermission.setPermissionId(permissionId);//根据资源父ID查询角色是否关联资源
        int count = sysPermissionService.queryRolePermissionId(sysPermission);
        ResultObject resultObject = new ResultObject(count, "已有关联数据", "无关联数据");
        return resultObject;//返回结果集
    }
}
